package cn.tedu.v1.service.impl;

import cn.tedu.v1.mapper.UserMapper;
import cn.tedu.v1.model.Permission;
import cn.tedu.v1.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userMapper.findUserByUsername(username);
        if (user == null) {
            return null;
        }
        List<Permission> permissions = userMapper.findUserPermissionsById(user.getId());
        String[] auth = new String[permissions.size()];
        int i = 0;
        for (Permission p : permissions) {
            auth[i++] = p.getName();
        }
        UserDetails u = org.springframework.security.core.userdetails
                .User
                .builder()
                .username(user.getUsername())
                .password(user.getPassword())
                .authorities(auth)
                .accountLocked(false)
                .disabled(false)
                .build();
        return u;
    }
}
